package cn.tedu.ivos.base.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private CustomUserDetailsService detailsService;

    //authenticate方法进行用户认证
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //authentication对象有用户名和密码
        String username = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();
        //利用从authentication对象中获取到的用户名，
        // 在CustomUserDetailsService中的loadUserByUsername方法中找对应的用户信息
        UserDetails userDetails = detailsService.loadUserByUsername(username);
        //判断userDetails中的密码和authentication中的密码是否匹配
        if(!userDetails.getPassword().equals(password))
            throw new BadCredentialsException("用户名或密码不正确，请重新登录");
        //如果认证成功，返回新的认证令牌(Token)
        return new UsernamePasswordAuthenticationToken(userDetails,password,userDetails.getAuthorities());
    }
    //需要判断是否支持该认证类型,true表示支持该类型
    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
